<template>
  <my-container v-loading="pageLoading">
    <!--顶部操作-->
    <template #header>
      <el-form class="ad-form-query" :inline="true" :model="filter" @submit.native.prevent>
        <el-form-item>
          <el-input
            v-model="filter.name"
            placeholder="用户名"
            clearable
            @keyup.enter.native="onSearch"
          >
            <template #prefix>
              <i class="el-input__icon el-icon-search" />
            </template>
          </el-input>
        </el-form-item>

        <el-form-item>
          <el-button icon="el-icon-search" type="warning" @click="onSearch">查询</el-button>
        </el-form-item>
        <el-form-item v-if="checkPermission(['admin_sysuser_add'])">
          <el-button icon="el-icon-plus" type="primary" @click="onAdd">新增</el-button>
        </el-form-item>
        <el-form-item v-if="checkPermission(['admin_sysuser_importexcel'])">
          <el-button icon="el-icon-document-add" type="warning" @click="importdata">Excel导入</el-button>
        </el-form-item>
        <el-form-item v-if="checkPermission(['admin_sysuser_downloadexcel'])">
          <el-button icon="el-icon-download" type="warning" @click="dowload">下载模板</el-button>
        </el-form-item>
        <el-form-item v-if="checkPermission(['admin_sysuser_delete'])">
          <my-confirm-button
            :disabled="sels.length === 0"
            :type="'delete'"
            :placement="'bottom-end'"
            :loading="deleteLoading"
            style="margin-left: 0px;"
            @click="onBatchDelete"
          >
            <template #content>
              <p>确定要批量删除吗？</p>
            </template>
            批量删除
          </my-confirm-button>
        </el-form-item>
      </el-form>
    </template>

    <!--列表-->
    <el-table
      v-loading="listLoading"
      border
      :data="users"
      highlight-current-row
      :header-cell-style="{background:'#f9f9f9'}"
      @selection-change="onSelsChange"
    >
      <el-table-column type="selection" width="50" />
      <el-table-column type="index" width="80" label="#" />
      <el-table-column prop="userName" label="用户名" width />
      <el-table-column prop="trueName" label="真实姓名" width />
      <el-table-column prop="orgName" label="部门" width />
      <el-table-column prop="roles" label="角色" width />
      <el-table-column prop="sex" label="性别" width>
        <template #default="{row}">
          {{ row.sex == 1 ? '女' : '男' }}
        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="创建时间" :formatter="formatCreatedTime" width />
      <el-table-column prop="status" label="状态" width>
        <template #default="{row}">
          <el-tag :type="row.status == 1 ? 'success' : 'danger'" disable-transitions>
            {{ row.status == 1 ? '正常' : '禁用' }}
          </el-tag>
        </template>
      </el-table-column>

      <el-table-column label="操作" width="260">
        <template #default="{ $index, row }">
          <el-button type="success" icon="el-icon-search" @click="pdfshow(row)">预览</el-button>
          <el-button v-if="checkPermission(['admin_sysuser_update'])" type="success" icon="el-icon-edit" @click="onEdit($index, row)">编辑</el-button>
          <my-confirm-button
            v-if="checkPermission(['admin_sysuser_delete'])"
            type="delete"
            icon="el-icon-delete"
            :loading="row._loading"
            :validate-data="row"
            @click="onDelete($index, row)"
          />
        </template>
      </el-table-column>

    </el-table>

    <my-pagination
      ref="pager"
      :total="total"
      :checked-count="sels.length"
      @get-page="getUsers"
    />

    <!--新增窗口-->
    <el-dialog
      title="新增用户"
      :visible.sync="addFormVisible"
      :close-on-click-modal="false"
      width="40%"
    >
      <el-form ref="addForm" :model="addForm" label-width="80px" :rules="addFormRules" size="medium">
        <el-row>
          <el-col :span="12">
            <el-form-item label="用户名" prop="userName">
              <el-input v-model="addForm.userName" auto-complete="off" />
            </el-form-item>

          </el-col>
          <el-col :span="12">
            <el-form-item label="密码" prop="password">
              <el-input v-model="addForm.password" type="password" auto-complete="off" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="真实姓名" prop="trueName">
              <el-input v-model="addForm.trueName" auto-complete="off" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="电话" prop="phone">
              <el-input v-model="addForm.phone" auto-complete="off" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="角色" prop="roles">
          <el-select v-model="addForm.roles" multiple placeholder="请选择角色" style="width:100%;">
            <el-option
              v-for="item in roles"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>

        <el-form-item prop="organizeId" label="部门">
          <el-cascader
            :key="addFormKey"
            v-model="addForm.organizeId"
            placeholder="请选择，支持搜索功能"
            :options="orgs"
            :props="{ checkStrictly: true, value: 'id'}"
            filterable
            style="width:100%;"
          />
        </el-form-item>

        <el-form-item label="联系地址" prop="adress">
          <el-input v-model="addForm.adress" auto-complete="off" />
        </el-form-item>

        <el-row>
          <el-col :span="5">
            <el-form-item label="启用" prop="status">
              <el-switch
                v-model="addForm.status"
                :active-value="1"
                :inactive-value="0"
              />

            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="性别">
              <el-radio-group v-model="addForm.sex">
                <el-radio :label="0">男</el-radio>
                <el-radio :label="1">女</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click.native="addFormVisible = false">取消</el-button>
          <my-confirm-button type="submit" :validate="addFormvalidate" :loading="addLoading" @click="onAddSubmit" />
        </div>
      </template>
    </el-dialog>
    <!--编辑窗口-->
    <el-dialog
      title="编辑用户"
      :visible.sync="editFormVisible"
      :close-on-click-modal="false"
      width="40%"
    >
      <el-form ref="editForm" :model="editForm" label-width="80px" :rules="editFormRules" size="medium">
        <el-row>
          <el-col :span="12">
            <el-form-item label="用户名" prop="userName">
              <el-input v-model="editForm.userName" auto-complete="off" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="真实姓名" prop="trueName">
              <el-input v-model="editForm.trueName" auto-complete="off" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="电话" prop="phone">
              <el-input v-model="editForm.phone" auto-complete="off" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="editForm.email" type="email" auto-complete="off" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="角色" prop="roles">
          <el-select v-model="editForm.roles" multiple placeholder="请选择角色" style="width:100%;">
            <el-option
              v-for="item in roles"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>

        <el-form-item prop="organizeId" label="部门">
          <el-cascader
            :key="editFormKey"
            v-model="editForm.organizeId"
            placeholder="请选择，支持搜索功能"
            :options="orgs"
            :props="{ checkStrictly: true, value: 'id'}"
            filterable
            style="width:100%;"
          />
        </el-form-item>

        <el-form-item label="联系地址" prop="adress">
          <el-input v-model="editForm.adress" auto-complete="off" />
        </el-form-item>

        <el-row>
          <el-col :span="5">
            <el-form-item label="启用" prop="status">
              <el-switch
                v-model="editForm.status"
                :active-value="1"
                :inactive-value="0"
              />

            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="性别">
              <el-radio-group v-model="editForm.sex">
                <el-radio :label="0">男</el-radio>
                <el-radio :label="1">女</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click.native="editFormVisible = false">取消</el-button>
          <my-confirm-button type="submit" :validate="editFormvalidate" :loading="editLoading" @click="onEditSubmit" />
        </div>
      </template>
    </el-dialog>

    <!--新增窗口-->
    <el-dialog
      title="选择文件"
      :visible.sync="importWindowVisible"
      :close-on-click-modal="false"
      width="30%"
    >
      <el-upload
        ref="upload"
        class="upload-demo"
        drag
        :auto-upload="false"
        action="#"
        :on-change="Change"
        multiple
      >
        <i class="el-icon-upload" />
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div slot="tip" class="el-upload__tip">只能上传后缀为xlsx/xls的文件</div>
      </el-upload>
      <template #footer>
        <div class="dialog-footer">
          <my-confirm-button type="submit" @click="onImportSubmit" />
        </div>
      </template>

    </el-dialog>

    <el-dialog
      title="pdf"
      :visible.sync="pdfVisible"
      width="60%"
    >
      <div>
        <embed :src="pdfUrl" type="application/pdf" style="width: 100%;height:600px;">
      </div>
    </el-dialog>
  </my-container>
</template>

<script>
import axios from 'axios'
import store from '@/store'
import { formatTime } from '@/utils'
import { getRoleListPage } from '@/api/admin/role'
import { getOrgTree } from '@/api/admin/organize'
import { getUserListPage, removeUser, batchRemoveUser, editUser, addUser, getUser, importData } from '@/api/admin/user'
import MyContainer from '@/components/my-container'
import MyConfirmButton from '@/components/my-confirm-button'

export default {
  name: 'Users',
  components: { MyContainer, MyConfirmButton },
  data() {
    return {
      filter: {
        name: ''
      },
      searchWindowVisible: false,
      users: [],
      roles: [],
      orgs: [],
      total: 0,
      sels: [], // 列表选中列
      listLoading: false,
      file: undefined,
      pageLoading: false,
      addFormKey: 1,
      pdfVisible: false,
      addDialogFormVisible: false,
      editFormVisible: false, // 编辑界面是否显示
      editLoading: false,
      importWindowVisible: false,
      pdfUrl: '',
      editFormKey: 1,
      editFormRules: {
        userName: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
        password: [{ required: true, message: '请输入密码', trigger: 'blur' }]
      },
      userNameReadonly: true,
      // 编辑界面数据
      editForm: {
        id: 0,
        userName: '',
        trueName: '',
        roles: [],
        status: 1,
        sex: 0,
        organizeId: ''
      },

      addFormVisible: false, // 新增界面是否显示
      addLoading: false,
      addFormRules: {
        userName: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
        password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
        roles: [
          { required: true, message: '请选择角色', trigger: 'change' }
        ],
        organizeId: [{ required: true, message: '请选择部门', trigger: 'change' }]
      },
      // 新增界面数据
      addForm: {
        userName: '',
        trueName: '',
        password: '',
        roles: [],
        status: 1,
        sex: 0,
        organizeId: ''
      },
      deleteLoading: false
    }
  },
  async mounted() {
    await this.getUsers()
  },
  methods: {

    pdfshow(row) {
      this.pdfUrl = `${process.env.VUE_APP_AUTHORITY}/api/admin/sysuser/GetPdf/?id=`
      this.pdfVisible = true
      this.pdfUrl += row.id
    },

    formatCreatedTime(row, column, time) {
      return formatTime(time, 'YYYY-MM-DD HH:mm')
    },
    // 查询
    onSearch(dynamicFilter) {
      this.$refs.pager.setPage(1)
      this.dynamicFilter = dynamicFilter
      this.getUsers()
    },
    importdata() {
      this.importWindowVisible = true
    },
    async onImportSubmit() {
      const formData = new FormData()
      if (this.file) {
        formData.append('file', this.file)
      } else {
        this.$message({
          message: '请先选择上传文件!',
          type: 'warning'
        })
        return
      }
      const config = {
        headers: {
          'Content-Type': 'multipart/form-data'
        }
      }
      importData(formData, config).then(res => {
        if (res.success) {
          this.$message({
            message: '操作成功!',
            type: 'success'
          })
          this.$refs.upload.clearFiles()
          this.importWindowVisible = false
        } else {
          this.$message({
            message: res.msg,
            type: 'error'
          })
        }
      })
    },
    Change(file, fileList) {
      this.file = file.raw
      return false
    },
    // 下载模板
    dowload() {
      axios({
        method: 'get',
        url: `${process.env.VUE_APP_BASE_API}/admin/sysuser/DownLoadExcel`,
        responseType: 'blob',
        headers: { 'Authorization': 'Bearer ' + store.getters.token }
      })
        .then(res => {
          // console.log('response: ', res)
          // new Blob([data])用来创建URL的file对象或者blob对象
          const url = window.URL.createObjectURL(new Blob([res.data]))
          // 生成一个a标签
          const link = document.createElement('a')
          link.style.display = 'none'
          link.href = url
          link.download = '人员导入模板' + '.xlsx'
          document.body.appendChild(link)
          link.click()
        })
        .catch(error => {
          console.log('response: ', error)
        })
    },
    // 获取用户列表
    async getUsers() {
      var pager = this.$refs.pager.getPager()
      const params = {
        ...pager,
        userName: this.filter.name
      }

      this.listLoading = true
      const res = await getUserListPage(params)
      this.listLoading = false

      if (res.code !== 1) {
        return
      }

      this.total = res.data.totalCount
      const data = res.data.rows
      data.forEach(d => {
        d._loading = false
      })
      this.users = data
    },
    async getRoleListPage() {
      const res = await getRoleListPage({ pagesize: 100, currentPage: 1 })
      if (res && res.code === 1) {
        this.roles = res.data.rows
      }
    },
    // 部门结构
    async loadOrgTree() {
      this.orgs = []
      const res = await getOrgTree()
      this.orgs.push(res.data[0])
    },
    // 显示编辑界面
    async onEdit(index, row) {
      if (this.roles.length === 0) {
        await this.getRoleListPage()
      }
      const res = await getUser({ id: row.id })
      this.pageLoading = false
      ++this.editFormKey
      await this.loadOrgTree()
      if (res && res.success) {
        const parentIds = []
        parentIds.push(res.data.organizeId)
        const data = res.data
        data.parentIds = parentIds
        this.editForm = data
        this.editFormVisible = true
      }
    },
    // 显示新增界面
    async onAdd() {
      if (this.roles.length === 0) {
        this.pageLoading = true
        await this.getRoleListPage()
        this.pageLoading = false
      }
      await this.loadOrgTree()
      this.addFormVisible = true
      ++this.addFormKey
    },
    closeAddForm() {
      this.$refs.addForm.resetFields()
    },
    // 编辑验证
    editFormvalidate() {
      let isValid = false
      this.$refs.editForm.validate(valid => {
        isValid = valid
      })
      return isValid
    },
    // 编辑
    async onEditSubmit() {
      this.editLoading = true
      const para = _.cloneDeep(this.editForm)
      if (Array.isArray(para.organizeId)) {
        para.organizeId = para.organizeId.pop()
      }
      const res = await editUser(para)
      this.editLoading = false

      if (!res?.success) {
        return
      }

      this.$message({
        message: this.$t('admin.updateOk'),
        type: 'success'
      })
      this.$refs['editForm'].resetFields()
      this.editFormVisible = false
      this.getUsers()
    },
    // 新增验证
    addFormvalidate() {
      let isValid = false
      this.$refs.addForm.validate(valid => {
        isValid = valid
      })
      return isValid
    },
    // 新增
    async onAddSubmit() {
      this.addLoading = true
      const para = _.cloneDeep(this.addForm)
      para.organizeId = para.organizeId.pop()
      const res = await addUser(para)
      this.addLoading = false

      if (!res?.success) {
        return
      }

      this.$message({
        message: this.$t('admin.addOk'),
        type: 'success'
      })
      this.$refs['addForm'].resetFields()
      this.addFormVisible = false
      this.getUsers()
    },
    // 删除
    async onDelete(index, row) {
      row._loading = true
      const para = []
      para.push(row.id)

      const res = await removeUser(para)
      row._loading = false

      if (!res?.success) {
        return
      }
      this.$message({
        message: this.$t('admin.deleteOk'),
        type: 'success'
      })
      this.getUsers()
    },

    // 批量删除
    async onBatchDelete() {
      const para = { ids: [] }
      para.ids = this.sels.map(s => {
        return s.id
      })

      this.deleteLoading = true
      const res = await batchRemoveUser(para.ids)
      this.deleteLoading = false

      if (!res?.success) {
        return
      }
      this.$message({
        message: this.$t('admin.batchDeleteOk'),
        type: 'success'
      })

      this.getUsers()
    },
    // 选择
    onSelsChange(sels) {
      this.sels = sels
    }
  }
}
</script>

<style lang="scss" scoped>
.my-search ::v-deep .el-input-group__prepend {
  background-color: #fff;
}
</style>
